package com.market.fleamarket.service;

import com.market.fleamarket.entity.Order;
import com.market.fleamarket.entity.Review;
import com.market.fleamarket.repository.OrderRepository;
import com.market.fleamarket.repository.ReviewRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.HashMap;

@Service
public class ReviewService {
    @Autowired
    private ReviewRepository reviewRepository;

    @Autowired
    private OrderRepository orderRepository;

    public Review save(Review review) {
        return reviewRepository.save(review);
    }

    public List<Review> findAll() {
        return reviewRepository.findAll();
    }

    public Optional<Review> findById(Long id) {
        return reviewRepository.findById(id);
    }

    /**
     * 通过订单ID查找评价
     * @param orderId 订单ID
     * @return 评价（如果存在）
     */
    public Optional<Review> findByOrderId(Long orderId) {
        return reviewRepository.findByOrder_Id(orderId);
    }

    @Transactional
    public Review addReview(Long orderId, Review review, Long reviewerId) {
        Order order = orderRepository.findById(orderId).orElseThrow(() -> new RuntimeException("订单不存在"));

        // 检查订单状态是否为已完成或已评价
        if (!("completed".equals(order.getStatus()) || "reviewed".equals(order.getStatus())))
            throw new RuntimeException("只能评价已完成订单");

        // 检查是否已有评价
        Optional<Review> existingReview = reviewRepository.findByOrder_Id(orderId);
        if (existingReview.isPresent()) {
            // 如果已有评价，则更新评价内容
            Review oldReview = existingReview.get();
            oldReview.setDescriptionScore(review.getDescriptionScore());
            oldReview.setResponseScore(review.getResponseScore());
            oldReview.setComment(review.getComment());
            return reviewRepository.save(oldReview);
        }

        // 新评价
        review.setOrder(order);
        review.setReviewer(order.getBuyer());
        Review savedReview = reviewRepository.save(review);

        // 更新订单状态为已评价
        order.setStatus("reviewed");
        orderRepository.save(order);

        return savedReview;
    }

    public Double getSellerAverageScore(Long sellerId) {
        Double avg = reviewRepository.findAverageScoreByUserId(sellerId);
        return avg == null ? 0.0 : avg;
    }

    /**
     * 获取商品的买家评分（基于responseScore字段）
     * @param productId 商品ID
     * @return 平均评分，如果没有评分则返回0.0
     */
    public Double getProductBuyerResponseScore(Long productId) {
        Double avg = reviewRepository.findAverageResponseScoreByProductId(productId);
        return avg == null ? 0.0 : avg;
    }

    public Page<Review> findByProductSeller(Long sellerId, Pageable pageable) {
        // 修正: 调用repository中针对特定卖家的查询方法
        return reviewRepository.findByOrderProductUserId(sellerId, pageable);
    }

    /**
     * 获取用户发表的所有评价
     * @param reviewerId 评价者ID
     * @return 评价列表
     */
    public List<Review> findByReviewerId(Long reviewerId) {
        return reviewRepository.findByReviewerId(reviewerId);
    }

    /**
     * 获取卖家商品的评价列表（适配前端显示需求）
     * @param sellerId 卖家ID
     * @return 包含评价信息的Map列表
     */
    public List<Map<String, Object>> findReviewsBySellerId(Long sellerId) {
        List<Review> reviews = reviewRepository.findBySellerIdForProductDetail(sellerId);

        // 转换为前端需要的数据格式
        return reviews.stream().map(review -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", review.getId());
            map.put("score", (review.getDescriptionScore() + review.getResponseScore()) / 2.0);
            map.put("comment", review.getComment());
            map.put("createdTime", review.getCreatedAt());

            // 添加买家信息
            Map<String, Object> buyer = new HashMap<>();
            if (review.getReviewer() != null) {
                buyer.put("id", review.getReviewer().getId());
                buyer.put("username", review.getReviewer().getUsername());
            } else {
                buyer.put("username", "匿名用户");
            }
            map.put("buyer", buyer);

            // 添加商品信息
            if (review.getOrder() != null && review.getOrder().getProduct() != null) {
                Map<String, Object> product = new HashMap<>();
                product.put("id", review.getOrder().getProduct().getId());
                product.put("name", review.getOrder().getProduct().getName());
                map.put("product", product);
            }

            return map;
        }).collect(java.util.stream.Collectors.toList());
    }

    /**
     * 获取特定商品的评价列表（适配前端显示需求）
     * @param productId 商品ID
     * @return 包含评价信息的Map列表
     */
    public List<Map<String, Object>> findReviewsByProductId(Long productId) {
        List<Review> reviews = reviewRepository.findByProductId(productId);

        // 转换为前端需要的数据格式
        return reviews.stream().map(review -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", review.getId());
            map.put("score", (review.getDescriptionScore() + review.getResponseScore()) / 2.0);
            map.put("comment", review.getComment());
            map.put("createdTime", review.getCreatedAt());

            // 添加买家信息
            Map<String, Object> buyer = new HashMap<>();
            if (review.getReviewer() != null) {
                buyer.put("id", review.getReviewer().getId());
                buyer.put("username", review.getReviewer().getUsername());
            } else {
                buyer.put("username", "匿名用户");
            }
            map.put("buyer", buyer);

            return map;
        }).collect(java.util.stream.Collectors.toList());
    }
}
 